//
//  shangjiajianjieViewController.m
//  YeDian
//
//  Created by 罗西 on 3/28/16.
//  Copyright © 2016 罗西. All rights reserved.
//

#import "zhaopinfabuViewController.h"
#import "Tools.h"
#import "ConfigData.h"
#import "ASIFormDataRequest.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "Toast+UIView.h"
#import "JSON.h"
#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"
#import "UIColor+Hex.h"
#import "BRPlaceholderTextView.h"

@interface zhaopinfabuViewController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate>{
    int code;
    NSDictionary *myInfoDic;
    NSData *data;
    NSArray *jobTitleData;
    NSString *job_title;
    UIButton *publishBtn;
    NSInteger photoCount;
    NSString *strDetail;
    NSString *job_type;
    UIButton *jobTypeBtn;
}

@property (nonatomic,strong) UITableView *mainTableView;
//@property (nonatomic,assign) BOOL isEditing;
@property (nonatomic,strong) NSString*  serverPath;
@property (nonatomic,strong) UIButton *imgBtn;
@property (nonatomic,strong) UIButton *btn;
@property (nonatomic,strong) NSString *avatar;
//@property (nonatomic,strong) NSArray *imgArray;
@property (nonatomic,strong) NSMutableArray *photoArray;
@property (nonatomic,strong) NSMutableArray *imgArray;
@property (nonatomic,strong) UIButton *selectBgView;
@property (nonatomic,strong) UISegmentedControl *control;

@end

@implementation zhaopinfabuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"发布招聘";
    
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    CGRect frame_img= CGRectMake(0,(44-19)/2,19,19);
    UIImageView* backView=[[UIImageView alloc] initWithFrame:frame_img];
    backView.image=[UIImage imageNamed:@"back2016"];
    CGRect frameBtn= CGRectMake(0, 0,50, 44);
    UIButton* homeBtn= [[UIButton alloc] initWithFrame:frameBtn];
    [homeBtn addTarget:self action:@selector(backFn) forControlEvents:UIControlEventTouchUpInside];
    [homeBtn addSubview:backView];
    UIBarButtonItem* barHomeBtn= [[UIBarButtonItem alloc] initWithCustomView:homeBtn];
    self.navigationItem.leftBarButtonItem=barHomeBtn;
    
    _control = [[UISegmentedControl alloc]initWithItems:@[@"酒吧",@"ktv",@"会所"]];
    _control.frame = CGRectMake(-3, 0, SCREEN_WIDTH+6, 30);
    _control.tintColor = [UIColor redColor];
    _control.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_control];
    _control.selectedSegmentIndex = 0;
    
    [_control addTarget:self action:@selector(controllerPressed:) forControlEvents:UIControlEventValueChanged];
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 30, SCREEN_WIDTH, SCREEN_HEIGHT-64-40) style:UITableViewStyleGrouped];
    [self.view addSubview:self.mainTableView];
    [self.mainTableView setDataSource:self];
    [self.mainTableView setDelegate:self];
    [self.mainTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.mainTableView setBackgroundColor:[UIColor colorWithRed:252/255.0 green:252/255.0 blue:252/255.0 alpha:1.0]];
    //self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *pushBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-40-64, SCREEN_WIDTH, 40)];
    [pushBtn setTitle:@"发布" forState:UIControlStateNormal];
    pushBtn.backgroundColor = [UIColor redColor];
    [self.view bringSubviewToFront:pushBtn];
    [self.view addSubview:pushBtn];
    [pushBtn addTarget:self action:@selector(fabu) forControlEvents:UIControlEventTouchUpInside];
    
    jobTitleData=@[@"DJ",
                   @"灯光", @"mc", @"舞台总监", @"舞编", @"A组ds", @"B组ds", @"服务员", @"咨客",
                   @"营销", @"服务员领班", @"总经理", @"副总经理", @"楼面经理", @"企划", @"收银员",
                   @"收银员", @"保安",@"男歌手",@"女歌手", @"其他"];
    job_title = @"DJ";
    _photoArray = [NSMutableArray new];
    _imgArray = [NSMutableArray new];
    job_type = @"1";
    [self loadData];
    
}

- (void) controllerPressed:(UISegmentedControl*)sender {
    job_type = [NSString stringWithFormat:@"%ld",(long)sender.selectedSegmentIndex+1];
    
}

-(void)fabu{
    NSLog(@"click");
    
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSString*  uid=[ud objectForKey:@"uid"];
    NSString* uidStr=[NSString stringWithFormat:@"%@",uid];
    NSString*  longi=[ud objectForKey:@"longitude"];
    NSString*  lati=[ud objectForKey:@"latitude"];
    
    NSString* loginURL=HOST;
    loginURL=[loginURL stringByAppendingString:@"index.php/AppRecruit/saveRecruit"];
    NSLog(@"保存URL.loginURL==%@",loginURL);
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    
    [req addPostValue:[NSString stringWithFormat:@"%@",longi] forKey:@"longi"];
    [req addPostValue:[NSString stringWithFormat:@"%@",lati] forKey:@"lati"];
    
    BRPlaceholderTextView *tf = [self.view viewWithTag:108];
    [req addPostValue:job_title forKey:@"title"];
    [req addPostValue:strDetail forKey:@"tj"];
    [req addPostValue:uidStr forKey:@"uid"];
    [req addPostValue:job_type forKey:@"recruit_type"];
    [req addPostValue:_userType forKey:@"user_type"];
    
    //NSString* tmpImg=[NSString stringWithFormat:@"%@",self.serverPath];
    //tmpImg=[tmpImg stringByAppendingString:@".jpg"];
    if (_photoArray.count > 0) {
        [req addPostValue:[NSString stringWithFormat:@"%@",[_photoArray objectAtIndex:0]] forKey:@"pic0"];
    }
    if (_photoArray.count > 1) {
        [req addPostValue:[NSString stringWithFormat:@"%@",[_photoArray objectAtIndex:1]] forKey:@"pic1"];
    }
    if (_photoArray.count > 2) {
        [req addPostValue:[NSString stringWithFormat:@"%@",[_photoArray objectAtIndex:2]] forKey:@"pic2"];
    }
    if (_photoArray.count > 3) {
        [req addPostValue:[NSString stringWithFormat:@"%@",[_photoArray objectAtIndex:3]] forKey:@"pic3"];
    }
    

    [req addPostValue:[NSString stringWithFormat:@"%ld",_control.selectedSegmentIndex+1] forKey:@"recruit_type"];
    
    
    
    [req startSynchronous];
    NSError *error = [req error];
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        
        NSString *response = [req responseString];
        NSLog(@"保存返回结果%@",response);
        
        NSDictionary* dic=[response JSONValue];
        code=[[dic objectForKey:@"pk"] intValue];
        if (code > 0) {
            [self.view makeToast:@"发布成功" duration:1.0 position:@"center"];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [self.view makeToast:@"发布失败" duration:1.0 position:@"center"];
        }
        [self performSelectorOnMainThread:@selector(finishFn) withObject:nil waitUntilDone:YES];
    }
}


-(void)backFn{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)doSaveOrderFn{
    //kdType
    
    UITextField *tf1 = [self.view viewWithTag:101];
    UITextField *tf2 = [self.view viewWithTag:102];
    UITextField *tf3 = [self.view viewWithTag:106];
    
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSString *str = [ud objectForKey:@"uid"];
    NSLog(@"str:%@",str);
    
    NSString* loginURL=HOST;
    loginURL=[loginURL stringByAppendingString:@"/index.php/appMerchant/updateMerchantFn"];
    NSLog(@"保存URL.loginURL==%@",loginURL);
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    //
    [req addPostValue:tf1.text forKey:@"mp"];//快递类型
    [req addPostValue:tf2.text forKey:@"addr"];
    [req addPostValue:[myInfoDic objectForKey:@"name"] forKey:@"name"];
    [req addPostValue:[myInfoDic objectForKey:@"qm"] forKey:@"qm"];
    
    [req addPostValue:[myInfoDic objectForKey:@"name"] forKey:@"name"];
    [req addPostValue:tf3.text forKey:@"description"];
    
    if (self.serverPath.length != 0) {
        
        NSString* tmpImg=[NSString stringWithFormat:@"/upload/%@",self.serverPath];
        NSLog(@"tmpImg:%@",tmpImg);
        [req addPostValue:tmpImg forKey:@"pic0"];
        
    }
    
    
    
    
    
    
    
    NSString*  uid=[ud objectForKey:@"uid"];
    
    [req addPostValue:[NSString stringWithFormat:@"%@",uid] forKey:@"merchant_id"];
    [req startSynchronous];
    NSLog(@"req:%@",req);
    NSError *error = [req error];
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        
        NSString *response = [req responseString];
        NSLog(@"保存返回结果%@",response);
        NSDictionary* dic=[response JSONValue];
        code=[[dic objectForKey:@"code"] intValue];
        [self performSelectorOnMainThread:@selector(finishFn) withObject:nil waitUntilDone:YES];
    }
    
}

-(void)finishFn{
//    if (code==1) {
//        [self.view makeToast:@"保存资料成功" duration:1.0 position:@"center"];
//        [self loadData];
//        
//    }else{
//        [self.view makeToast:@"保存资料失败" duration:1.0 position:@"center"];
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"showTab" object:nil];
//    }
}

-(void)loadData{
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString* mp_ = [accountDefaults objectForKey:@"uid"];
    //NSString* mp_=[ud objectForKey:@"mp"];
    if (!mp_) {
        return;
    }
    NSLog(@"mp:%@",mp_);
    NSString* loginURL=HOST;
    loginURL=[loginURL stringByAppendingString:@"/index.php/appMerchant/loadMerchantInfo?merchantId="];
    loginURL=[loginURL stringByAppendingFormat:@"%@",mp_];
    NSLog(@"保存URL.loginURL==%@",loginURL);
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    
    
    [req startSynchronous];
    NSError *error = [req error];
    
    
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        
        NSString *response = [req responseString];
        NSLog(@"保存返回结果%@",response);
        myInfoDic=[response JSONValue];
        NSString* uid=[myInfoDic objectForKey:@"uid"];
        NSLog(@"ID%@",uid);
        
        //加载图片
        NSString* loginURL=HOST;
        loginURL=[loginURL stringByAppendingString:@"/index.php/UserImg/findUserImgList?uid="];
        loginURL=[loginURL stringByAppendingFormat:@"%@",mp_];
        NSLog(@"保存URL.loginURL==%@",loginURL);
        NSURL* url=[[NSURL alloc] initWithString:loginURL];
        ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
        
        
        [req startSynchronous];
        error = [req error];
        
        if (!error) {
            NSString *response = [req responseString];
            //_imgArray = [response JSONValue];
            
            [self.mainTableView reloadData];
            
        }
        
        
        //[self performSelectorOnMainThread:@selector(finishLoadMyInfoFn) withObject:nil waitUntilDone:YES];
    }else{
        NSLog(@"move failed:%@", [error localizedDescription]);
    }
}

-(void)textViewDidChange:(UITextView *)textView{
    strDetail = textView.text;
}

#pragma mark UITableViewDelegate/UITableViewDataSource

/**
 *  每个cell有多少行
 */
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}


/**
 *  有多少个section
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (_photoArray.count >3) {
        return 7;
    }
    return 4+_photoArray.count;
}

/**
 *  section的title
 */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    return nil;
}

/**
 *  header的距离
 */
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 10;
    
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}

/**
 *  row的高度
 */
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 80;
    }else if(indexPath.section == 2){
        return 100;
    }else if (indexPath.section < 3){
        return 44;
    }    else if (indexPath.section >= 3){
        return SCREEN_WIDTH-40+20;
    }
    return 44;
}

/**
 *  cell的属性
 */
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [UITableViewCell new];
    
    NSArray *array = @[@"职位",@"详情"];
    NSArray *array2 = @[@"DJ",@"请输入招聘详情"];
    UILabel *TitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 15, 30, 12)];
    if (indexPath.section == 0){
        
        NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
        NSDictionary *dic_mes = [accountDefaults objectForKey:@"myInfoDic"];
        
        NSLog(@"userType:%@",[dic_mes objectForKey:@"user_type"]);
        
        UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(30, 10, 60, 60)];
        imgView.backgroundColor = [UIColor lightGrayColor];
        
            [imgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST,[dic_mes objectForKey:@"logo"]]] placeholderImage:[UIImage new]];

        
        [cell addSubview:imgView];
        imgView.backgroundColor = [UIColor lightGrayColor];
        
        NSString *str_qm = [dic_mes objectForKey:@"qm"];
        NSString *str_name = [dic_mes objectForKey:@"name"];
        
        if ([[dic_mes objectForKey:@"user_type"]intValue] == 1) {
            
            if ((![[dic_mes objectForKey:@"avatar"] isEqual:[NSNull null]])&&[[dic_mes objectForKey:@"avatar"] rangeOfString:@"http"].location != NSNotFound) {
                [imgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[dic_mes objectForKey:@"avatar"]]] placeholderImage:[UIImage new]];
            }else{
                [imgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST,[dic_mes objectForKey:@"avatar"]]] placeholderImage:[UIImage new]];
            }
//            [imgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST,[dic_mes objectForKey:@"avatar"]]] placeholderImage:[UIImage new]];
            
            str_qm = [dic_mes objectForKey:@"qm"];
            str_name = [dic_mes objectForKey:@"nickname"];
        }
        
        
        
        if ([str_qm isEqual:[NSNull null]]||str_qm.length == 0) {
            str_qm = @"";
        }
        if ([str_name isEqual:[NSNull null]]||str_name.length == 0) {
            str_name = @"";
        }
        
        UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(110, 10, 200, 30)];
        nameLabel.text = [NSString stringWithFormat:@"%@",str_name];
        nameLabel.font = [UIFont systemFontOfSize:20];
        [cell addSubview:nameLabel];
        
        UILabel *nameLabel2 = [[UILabel alloc]initWithFrame:CGRectMake(110, 50, 200, 15)];
        NSString *str = [NSString stringWithFormat:@"%@",str_qm];
        nameLabel2.text = [NSString stringWithFormat:@"%@",str.length == 0?@"":str];
        nameLabel2.font = [UIFont systemFontOfSize:13];
        [cell addSubview:nameLabel2];
        

        
        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }else
        if(indexPath.section != 3 && indexPath.section<4){
            TitleLabel.center = CGPointMake(TitleLabel.center.x, cell.center.y);
            TitleLabel.text = [array objectAtIndex:indexPath.section-1];
            TitleLabel.font = [UIFont systemFontOfSize:13];
            
        }
    [cell addSubview:TitleLabel];
    
    if (indexPath.section == 1 ||indexPath.section == 2){
        UITextField *tf = [[UITextField alloc]initWithFrame:CGRectMake(80, 5, 200, 34)];
        
        tf.font = [UIFont systemFontOfSize:13];
        
        if(indexPath.section == 1){
            //tf.text = [myInfoDic objectForKey:@"mp"];
            publishBtn = [[UIButton alloc]initWithFrame:CGRectMake(80, 5, 200, 34)];
            [publishBtn setTitle:job_title forState:UIControlStateNormal];
            [publishBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            publishBtn.titleLabel.font = [UIFont systemFontOfSize:13];
            publishBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
            publishBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            [publishBtn addTarget:self action:@selector(jobTypeSelete) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:tf];
            [cell addSubview:publishBtn];
            
            //tf.tag = 999;
        }else if (indexPath.section == 2){
            //tf.text = [myInfoDic objectForKey:@"addr"];
            tf.placeholder = [array2 objectAtIndex:indexPath.section-1];
            tf.text = strDetail;
            
            BRPlaceholderTextView *tv = [[BRPlaceholderTextView alloc]initWithFrame:CGRectMake(80, 5, SCREEN_WIDTH-100, 90)];
            tv.placeholder = @"请输入详情";
            tv.layer.borderColor = [UIColor lightGrayColor].CGColor;
            tv.layer.borderWidth = 1.0f;
            [cell addSubview:tv];
            tv.tag = 108;
            tv.text = strDetail;
            tv.delegate = self;
        }
        
        tf.tag = 100+indexPath.section;
    }else if(indexPath.section >= 3){
        

        
        _btn = [[UIButton alloc]initWithFrame:CGRectMake(20, 0, SCREEN_WIDTH-40, (SCREEN_WIDTH-40))];
        _btn.layer.borderColor = [UIColor orangeColor].CGColor;
        
        [_btn addTarget:self action:@selector(paiZhaoFn) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:_btn];
        
        _btn.tag = 8888+indexPath.section;
        
        if (indexPath.section < _photoArray.count+3) {
            _btn.userInteractionEnabled = NO;
            [_btn setImage:[_imgArray objectAtIndex:indexPath.section-3] forState:UIControlStateNormal];
            [_btn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        }else{
            _btn.userInteractionEnabled = YES;
            [_btn setImage:[UIImage imageNamed:@"add_pic"] forState:UIControlStateNormal];
            [_btn setImageEdgeInsets:UIEdgeInsetsMake(100, 100, 100, 100)];
        }
        return cell;
    }
    
    return cell;
}

-(void)jobTypeSelete{
    if (!_selectBgView) {
        _selectBgView = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        [self.view addSubview:_selectBgView];
        _selectBgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
        [_selectBgView addTarget:self action:@selector(removeJobTypeBTN) forControlEvents:UIControlEventTouchUpInside];
        
        UIScrollView* sv=[[UIScrollView alloc] initWithFrame:CGRectMake(40,30, SCREEN_WIDTH-80 , SCREEN_HEIGHT-64-30)];
        sv.contentSize = CGSizeMake(SCREEN_WIDTH-80, 40*jobTitleData.count);
        sv.backgroundColor = [UIColor whiteColor];
        sv.showsHorizontalScrollIndicator = YES;
        sv.delegate = self;
        [_selectBgView addSubview:sv];
        
        for(int i=0;i<jobTitleData.count;i++){
            UIButton* btn=[[UIButton  alloc] initWithFrame:CGRectMake(0, 40*i, SCREEN_WIDTH-80, 40)];
            [btn addTarget:self action:@selector(selectTypeFn:) forControlEvents:UIControlEventTouchUpInside];
            btn.tag=8000+i;
            [sv addSubview:btn];
            
            NSString*  str=jobTitleData[i];
            UILabel*  yzLb=[[UILabel alloc] initWithFrame:CGRectMake(0,0, SCREEN_WIDTH-80, 39.5)];
            yzLb.text=str;
            yzLb.textColor=[UIColor orangeColor];
            yzLb.font=[UIFont systemFontOfSize:13];
            yzLb.textAlignment=NSTextAlignmentCenter;
            [btn addSubview:yzLb];
            //
            UIImageView* line=[[UIImageView alloc] initWithFrame:CGRectMake(0,39.5, SCREEN_WIDTH-80, 0.5)];
            line.layer.backgroundColor=[[UIColor colorWithHexString:@"bfbfbf"] CGColor];
            [btn addSubview:line];
        }
    }
    
    
}

-(void)selectTypeFn:(UIButton*)btn{
    long tag=btn.tag-8000;
    job_title=jobTitleData[tag];
    //UITextField *tf = [self.view viewWithTag:999];
    //tf.text = [NSString stringWithFormat:@"%@%@",job_title,@""];
    [publishBtn setTitle:job_title forState:UIControlStateNormal];
    if (_selectBgView) {
        [_selectBgView removeFromSuperview];
        _selectBgView = nil;
    }
    //[table reloadData];
    
    
}

-(void)removeJobTypeBTN{
    if (_selectBgView) {
        [_selectBgView removeFromSuperview];
        _selectBgView = nil;
    }
}

-(void)paiZhaoFn2{
    //_isAvatar = YES;
    [self paiZhaoFn];
}

-(void)addPhoto{
    //_isAvatar = NO;
    [self paiZhaoFn];
}

/**
 *  点击事件
 */
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)paiZhaoFn{
    
//    BRPlaceholderTextView *tf = [self.view viewWithTag:108];
//    strDetail = tf.text;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        UIActionSheet *chooseImageSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
        [chooseImageSheet showInView:self.view];
        
    }else{
        // [[NSNotificationCenter defaultCenter] postNotificationName:@"paidanFn" object:nil];
        
        
        UIActionSheet *chooseImageSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
        [chooseImageSheet showInView:self.view];
    }
    
}
#pragma mark UIActionSheetDelegate Method
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    UIImagePickerController * picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    switch (buttonIndex) {
        case 0://Take picture
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"hideTab" object:nil];
            
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                
            }else{
                NSLog(@"模拟器无法打开相机");
            }
            [self presentModalViewController:picker animated:YES];
            break;
            
        case 1://From album
            [[NSNotificationCenter defaultCenter] postNotificationName:@"hideTab" object:nil];
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentModalViewController:picker animated:YES];
            break;
            
        default:
            //[self dismissModalViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"showTab" object:nil];
            break;
    }
}

#pragma 拍照选择照片协议方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    [UIApplication sharedApplication].statusBarHidden = YES;
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        CGSize newSize=CGSizeMake(160, 160);
        newSize=CGSizeMake(SCREEN_WIDTH-40, SCREEN_WIDTH-40);
        image=[self smallImg:image scaledToSize:newSize];
        
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else
        {
            data = UIImagePNGRepresentation(image);
        }
        
        //long section = 8888+_photoArray.count+3;
        //UIButton *btn = [self.view viewWithTag:section];
        //[btn setImage:image forState:UIControlStateNormal];
        [_imgArray addObject:image];
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.jpg"] contents:data attributes:nil];
        
        //得到选择后沙盒中图片的完整路径
        NSString* filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.jpg"];
        NSLog(@"filePath:%@",filePath);
        
        
        self.avatar=filePath;
        
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];
        //[picker dismissModalViewControllerAnimated:YES];
        
        //创建一个选择后图片的小图标放在下方
        //类似微薄选择图后的效果
        
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showTab" object:nil];
        
        [self savePhotoFn];
        
    }
}

-(void)savePhotoFn{
    //NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString* uploadURL=@"yw_uploadify.php";
    uploadURL=[HOST stringByAppendingString:uploadURL];
    
    //NSLog(@"uploadURL=%@",uploadURL);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:uploadURL]];
    
    NSDate* now = [NSDate date];
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    
    fmt.dateFormat = @"yyyyMMddHHmmss";
    NSString* dateString = [fmt stringFromDate:now];
    NSLog(@"%@", dateString);
    
    
    self.serverPath=[Tools md5:dateString];
    
    
    
    
    [request setPostValue:[NSString stringWithFormat:@"%@",self.serverPath] forKey:@"serverImgName"];
    
    NSLog(@".....serverPath=%@", self.serverPath);
    
    self.serverPath=[self.serverPath stringByAppendingString:@".jpg"];
    [_photoArray addObject:self.serverPath];
    [self.mainTableView reloadData];
    [request setFile:self.avatar  forKey:@"filename"];
    
    
    
    //[request setValue:uid forKey:@"uid"];
    request.delegate = self;
    //
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [[MBProgressHUD showHUDAddedTo:app.window animated:YES] setLabelText:@"正在处理中，请稍后..."];
    
    
    
    
    [request startAsynchronous];
    
    
    [self savrMyAvatarFn];
}

-(void)savrMyAvatarFn{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *uid=[userDefaults objectForKey:@"uid"];
    NSString* strFlag=[userDefaults objectForKey:@"flag"];
    int flag=[strFlag intValue];
    
    
    [self.view makeToast:@"照片保存成功!"
                duration:1.0
                position:[NSValue valueWithCGPoint:CGPointMake(160, 210)]
     ];
    //NSDictionary* dic=[NSDictionary dictionaryWithObject:self.avatar forKey:@"avatar"];
    
    
    
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [MBProgressHUD hideHUDForView:app.window animated:YES];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"showTab" object:nil];
    
    //if(!_isAvatar)
    {
        NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
        NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
        NSString* mp_ = [accountDefaults objectForKey:@"phone"];
        //NSString* mp_=[ud objectForKey:@"mp"];
        if (!mp_) {
            return;
        }
        NSLog(@"mp:%@",mp_);
        NSString* loginURL=HOST;
        loginURL=[loginURL stringByAppendingString:@"index.php/UserImg/saveImg"];
        NSLog(@"保存URL.loginURL==%@",loginURL);
        NSURL* url=[[NSURL alloc] initWithString:loginURL];
        ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
        
        NSString*  uid2=[ud objectForKey:@"uid"];
        
        [req addPostValue:[NSString stringWithFormat:@"%@",uid2] forKey:@"uid"];
        
        NSString* tmpImg=[NSString stringWithFormat:@"%@",self.serverPath];
        NSLog(@"tmpImg:%@",tmpImg);
        [req addPostValue:[NSString stringWithFormat:@"/upload/%@",tmpImg] forKey:@"img_path"];
        
        [req startSynchronous];
        NSError *error = [req error];
        
        
        if (!error) {
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [MBProgressHUD hideHUDForView:app.window animated:YES];
            
            NSString *response = [req responseString];
            NSLog(@"保存返回结果%@",response);
            myInfoDic=[response JSONValue];
            NSString* uid=[myInfoDic objectForKey:@"uid"];
            NSLog(@"ID%@",uid);
            
            
            //[self.mainTableView reloadData];
            [self loadData];
            //[self performSelectorOnMainThread:@selector(finishLoadMyInfoFn) withObject:nil waitUntilDone:YES];
        }else{
            NSLog(@"move failed:%@", [error localizedDescription]);
        }
    }
    
    
}

-(UIImage*)smallImg:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
